package com.tianjishuju.cimiss.station.station.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * common object convert tools
 * 
 * @author Jax
 *
 */
public class ConvertUtil {

	private final static ObjectMapper OBJECT_MAPPER = ObjectMapperUtil.getObjectMapperForRouting();

	public static <T> List<T> mapListToObjectList(List<Map<String, Object>> mapList, Class<T> beanClass) {
		List<T> listResult = new ArrayList<T>();

		if(mapList != null && mapList.size() < 1) {
			return listResult;
		}

		for(Map<String, Object> eachMap: mapList) {
			T bean = mapToObject(eachMap, beanClass);
			if(bean == null) continue;
			listResult.add(bean);
		}

		return listResult;
	}

	public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) {
		return objectToObj(map, beanClass);
	}

	public static <T> T jsonStrToObject(String jsonStr, Class<T> beanClass) {
		try {
			if(ObjUtil.isEmpty(jsonStr)) return null;

			return OBJECT_MAPPER.readValue(jsonStr, beanClass);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static <T> T objectToObj(Object obj, Class<T> beanClass) {
		if(obj == null) return null;

		if(obj instanceof String) return jsonStrToObject(obj.toString(), beanClass);

		return jsonStrToObject(objectToStr(obj), beanClass);
	}

	public static String objectToStr(Object obj) {
		try {
			if(obj == null) return null;

			return OBJECT_MAPPER.writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
